package pro.cherish.smartfile.config.aspect;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.*;
import org.slf4j.MDC;
import org.springframework.stereotype.Component;
import pro.cherish.smartfile.common.constant.CommonConstants;

import java.util.UUID;

/**
 * 自定义日志切面
 *
 * @author lys
 */
@Aspect
@Component
public class LogAspect {

    private final static String SESSION_ID = "sessionId";

    /**
     * 自定义切点
     */
    @Pointcut("@annotation(pro.cherish.smartfile.common.annotation.LogId)")
    public void pointCut() {
    }

    /**
     * 前置通知-记录请求信息
     *
     * @param joinPoint
     */
    @Before("pointCut()")
    public void doBeforeAdvice(JoinPoint joinPoint) {
        // MDC容器增加requestId
        String uuid = UUID.randomUUID().toString().replaceAll("-", "");
        MDC.put(CommonConstants.SESSION_ID, uuid);
    }

    /**
     * 后置通知-记录返回信息
     *
     * @param joinPoint
     * @param result
     */
    @AfterReturning(pointcut = "pointCut()", returning = "result")
    public void doAfterReturningAdvice(JoinPoint joinPoint, Object result) {
        MDC.remove(SESSION_ID);
    }

    /**
     * 后置异常通知-记录返回出现异
     *
     * @param joinPoint
     * @param exception
     */
    @AfterThrowing(value = "pointCut()", throwing = "exception")
    public void doAfterThrowingAdvice(JoinPoint joinPoint, Throwable exception) {
        MDC.remove(SESSION_ID);
    }

}
